<template>
  <div class="promission">
    <!-- <a-form layout="inline" :form="form" @submit="handleSearch">

    <a-form-item label="用户名：" >
      <a-input v-decorator="['userName']" ></a-input>
    </a-form-item>

    <a-form-item label="密码：" >
      <a-input v-decorator="['password']" >
       
      </a-input>
    </a-form-item>

     <a-form-item label="昵称：" >
      <a-input v-decorator="['nikeName']">
       
      </a-input>
    </a-form-item>

    <a-form-item >
      <a-button type="primary" html-type="submit">
          查询
      </a-button>
    </a-form-item>
    
  </a-form> -->
    <a-button type="primary" @click="showModal = true">
      新增角色
    </a-button>
    <a-table :loading="loading" :columns="columns" :data-source="dataSource" rowKey="id" style="margin-top:20px">
      <template slot="createTime" slot-scope="text, record">
        <span>{{ $moment(new Date(record.createTime)).format("YYYY-MM-DD HH:mm:ss")}}</span>
      </template>

      <div v-if="record.editable" slot="authList" slot-scope="text, record, index">
        <a-select mode="multiple" v-model="record.authList" @change="e => handleChange(e ,index)" style="width: 100%"
          placeholder="请选择权限">
          <a-select-option v-for="(i,index) in translateAuth" :key="index">
            {{ i }}
          </a-select-option>
        </a-select>
      </div>
      <span v-else slot="authList" slot-scope="text, record">
        <a-tag v-for="(item,index) in record.authList" :key="index">{{translateAuth[item]}}</a-tag>
      </span>

      <template slot="operation" slot-scope="text, record ,index">
        <span v-if="record.editable" style="margin-right:10px">
          <a @click="() => save(record)" style="margin-right:10px">保存</a>
          <a-popconfirm title="确定取消?" @confirm="() => cancel(index)">
            <a>取消</a>
          </a-popconfirm>
        </span>
        <span v-else style="margin-right:10px">
          <a :disabled="editingKey !== ''" @click="() => edit(index)">编辑</a>
        </span>
        <a-popconfirm v-if="dataSource.length" title="确定删除这个角色?" @confirm="() => onDelete(record ,index)">
          <a href="javascript:;">删除</a>
        </a-popconfirm>
      </template>
    </a-table>
    <!-- 弹窗 -->
    <a-modal title="新增角色" :visible="showModal" @ok="handleOk" @cancel="handleCancel">
      <div>
        <a-form :form="form">

          <a-form-item label="角色名称:">
            <a-input v-decorator="['role']"></a-input>
          </a-form-item>

          <a-form-item label="权限列表:">
            <a-select v-decorator="['authList',{ rules: [{ required: true, message: '角色权限不能为空!' }] }]" mode="multiple"
              style="width: 100%" placeholder="请选择权限">
              <a-select-option v-for="(i,index) in translateAuth" :key="index">
                {{ i }}
              </a-select-option>
            </a-select>
          </a-form-item>
        </a-form>
      </div>
    </a-modal>

  </div>
</template>

<script>
  import {
    mapState
  } from 'vuex'
  import {
    translateAuth
  } from '../../utils/util'
  import {
    getRoleList,
    roleAdd,
    roleDel
  } from '@/services/promission.js'
  import {
    roleUpdate,
  } from '@/services/user.js'
  export default {
    name: 'Promission',
    components: {},
    computed: {
      ...mapState('setting', ['pageMinHeight']),
    },
    data() {
      return {
        translateAuth, // 权限对应数组
        showModal: false, // 弹窗
        loading: false,
        form: this.$form.createForm(this, {
          name: 'advanced_search'
        }),
        userId: JSON.parse(localStorage.getItem('admin.user')).userId,
        editingKey: '',
        columns: [{
            title: '角色名称',
            dataIndex: 'role',
            key: 'role',
          },
          {
            title: '创建时间',
            dataIndex: 'createTime',
            key: 'createTime',
            scopedSlots: {
              customRender: 'createTime'
            },
          },
          {
            title: '角色权限列表',
            dataIndex: 'authList',
            key: 'authList',
            scopedSlots: {
              customRender: 'authList'
            },
          },
          {
            title: '操作',
            dataIndex: 'operation',
            scopedSlots: {
              customRender: 'operation'
            },
          },
        ],
        dataSource: [],
      }
    },
    mounted() {
      this.getRoleTableData()
    },
    methods: {
      /**
       * 查询表格
       */
      getRoleTableData() {
        this.loading = true
        this.editingKey = ''
        let formData = new FormData()
        formData.append('userId', this.userId)
        getRoleList(formData).then(res => {
          this.loading = false
          this.dataSource = res.data.result.map(item => {
            item.editable = false
            item.authList = item.authList.map(item => Number(item))
            return item
          })
        })
      },
      edit(key) {
        this.dataSource[key].editable = true
        this.editingKey = key;
      },
      save(record) {
        let formData = new FormData()
        formData.append('userId', this.userId)
        formData.append('role', record.role)
        formData.append('authList', record.authList.toString())
        formData.append('id', record.id)
        roleUpdate(formData).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.result);
            this.getRoleTableData()
          }
        })
        this.editingKey = '';
      },
      cancel(key) {
        this.dataSource[key].editable = false
        this.editingKey = '';

      },
      //表格权限修改
      handleChange(text, record, index) {
        console.log(text, record, index, ',,,,,,,,,,,,,,,,./');
      },
      //删除角色
      onDelete(record, index) {
        let formData = new FormData()
        formData.append('userId', this.userId)
        formData.append('id', record.id)
        roleDel(formData).then(res => {

          if (res.data.code === 200) {
            this.$message.success(res.data.result);
            this.getRoleTableData()
          } else {
            this.$message.error(res.data.result);
          }
        })
        // const dataSource = [...this.dataSource];
        // this.dataSource = dataSource.filter(item => item.key !== key);
      },
      // set rola
      handleOk() {
        let role, authList,
          formData = new FormData()
        this.form.validateFields((error, values) => {
          console.log('Received values of form: ', values);
          role = values.role
          authList = values.authList
        });
        formData.append('userId', this.userId)
        formData.append('role', role)
        formData.append('authList', authList.toString())
        roleAdd(formData).then(res => {
          if (res.data.code === 200) {
            this.$message.success(res.data.result);
            this.handleCancel()
            this.getRoleTableData()
          } else {
            this.$message.error(res.result);
          }
        })
      },
      /**
       * 关闭弹窗
       */
      handleCancel() {
        this.showModal = false
      },
      // handleSearch(e) {
      //   this.form.validateFields((error, values) => {
      //     console.log('Received values of form: ', values);
      //   });
      // },
    }

  }
</script>

<style scoped lang="less">
  .promission {
    background-color: @base-bg-color;
    padding: 24px;
  }
</style>